import React, {useCallback, useState} from 'react'
import {Card, Form, Input, message, Modal, Radio, Select, Space} from 'antd'
import DataSourceTree from '@components/business/DataSourceTree'
import CatalogDetailView from './CatalogDetailView'
import DatabaseDetailView from './DatabaseDetailView'
import TableDetailView from './TableDetailView'
import type {CatalogSaveVo, ConnectType, DatabaseType, DataSourceTreeNode} from '@/types/source'
import {sourceApi} from '@services/api/source'
import styles from '../styles.module.css'

export default function DataSourceCenterView() {
  const [selectedNode, setSelectedNode] = useState<DataSourceTreeNode | null>(null)
  const [reloadKey, setReloadKey] = useState<number>(0)
  const [openCreate, setOpenCreate] = useState(false)
  const [creating, setCreating] = useState(false)
  const [form] = Form.useForm<CatalogSaveVo>()

  const handleOpenCreate = useCallback(() => setOpenCreate(true), [])
  const handleCancelCreate = useCallback(() => setOpenCreate(false), [])

  const handleSubmitCreate = useCallback(async () => {
    try {
      const values = await form.validateFields()
      const payload: CatalogSaveVo = {
        catalogName: values.catalogName,
        host: values.host,
        port: Number(values.port),
        databaseType: values.databaseType as DatabaseType,
        route: values.route,
        userName: values.userName,
        password: values.password,
        connectType: values.connectType as ConnectType,
        dorisCatalogName: values.dorisCatalogName,
        defaultSystemCode: values.defaultSystemCode,
      }
      setCreating(true)
      await sourceApi.addCatalog(payload)
      message.success('数据源已添加')
      setOpenCreate(false)
      form.resetFields()
      setReloadKey(Date.now())
    } catch (e: any) {
      if (e?.errorFields) return // 表单校验错误
      message.error(e?.message || '添加失败')
    } finally {
      setCreating(false)
    }
  }, [form])
  return (
    <div className={styles.page}>
      <div className={styles.grid} style={{ gridTemplateColumns: '240px 1fr' }}>
        {/* 树面板 */}
        <div className={styles.leftPanel}>
          <Card size="small" title="数据源树">
            <DataSourceTree
              onCreateCatalog={handleOpenCreate}
              onSelectNode={useCallback((n) => setSelectedNode(n), [])}
              reloadKey={reloadKey}
            />
          </Card>
        </div>

        {/* 主操作区 */}
        <div className={styles.mainPanel}>
          <Space direction="vertical" size="small" style={{ width: '100%' }}>
            <CatalogDetailView selectedNode={selectedNode} onUpdated={useCallback(() => setReloadKey(Date.now()), [])} />
            <DatabaseDetailView selectedNode={selectedNode} onUpdated={useCallback(() => setReloadKey(Date.now()), [])} />
            <TableDetailView selectedNode={selectedNode} onUpdated={useCallback(() => setReloadKey(Date.now()), [])} />
          </Space>
        </div>
      </div>

      <Modal
        title="新建数据源"
        open={openCreate}
        onCancel={handleCancelCreate}
        onOk={handleSubmitCreate}
        confirmLoading={creating}
        okText="提交"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item name="catalogName" label="数据源名称" rules={[{ required: true }]}> 
            <Input placeholder="如：巡检系统" />
          </Form.Item>
          <Form.Item name="databaseType" label="数据库类型" rules={[{ required: true }]}> 
            <Select placeholder="请选择数据库类型" options={[
              { label: 'MySQL', value: 'MYSQL' },
              { label: 'Oracle', value: 'ORACLE' },
              { label: 'PostgreSQL', value: 'POSTGRESQL' },
              { label: 'SQLServer', value: 'SQLSERVER' },
            ]} />
          </Form.Item>
          <Form.Item name="host" label="主机" rules={[{ required: true }]}> 
            <Input placeholder="如：192.168.1.100" />
          </Form.Item>
          <Form.Item name="port" label="端口" rules={[{ required: true }]}> 
            <Input type="number" placeholder="如：3306" />
          </Form.Item>
          <Form.Item name="route" label="路由/服务名" rules={[{ required: true }]}> 
            <Input placeholder="如：inspection_db 或服务名" />
          </Form.Item>
          <Form.Item name="connectType" label="连接类型" initialValue="SERVICE_NAME"> 
            <Radio.Group>
              <Radio value="SERVICE_NAME">ServiceName</Radio>
              <Radio value="SID">SID</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="userName" label="用户名" rules={[{ required: true }]}> 
            <Input placeholder="数据库用户名" />
          </Form.Item>
          <Form.Item name="password" label="密码" rules={[{ required: true }]}> 
            <Input.Password placeholder="数据库密码" />
          </Form.Item>
          <Form.Item name="dorisCatalogName" label="Doris Catalog 名称" rules={[{ required: true }]}> 
            <Input placeholder="如：inspection_doris" />
          </Form.Item>
          <Form.Item name="defaultSystemCode" label="默认系统编码" rules={[{ required: true }]}> 
            <Input placeholder="如：INSPECTION" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}